package com.xdtech.parking.controller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xdtech.sys.aspect.SystemControllerLog;
import com.xdtech.thirdapi.weixin.WeiXinPayUtil;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.jce.provider.JDKKeyFactory.RSA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xdtech.common.utils.DateUtil;
import com.xdtech.common.utils.DateUtil.DateStyle;
import com.xdtech.common.utils.encrypt.DESCoder;
import com.xdtech.forum.vo.MemberItem;
import com.xdtech.parking.service.ParkOrderInfoService;
import com.xdtech.parking.service.ParkUserService;
import com.xdtech.parking.service.ParkingDeviceService;
import com.xdtech.parking.vo.BillDetail;
import com.xdtech.parking.vo.ParkUserItem;
import com.xdtech.web.model.Pagination;
import com.xdtech.web.model.ResultMessage;
import com.xdtech.web.util.AppReturnUtils;

/**
 * 
 * @author max.zheng
 * @create 2015-06-21 14:00:53
 * @since 1.0
 * @see
 */
@Controller
@Scope("prototype")
public class ParkUserController {
	private Log log = LogFactory.getLog(ParkUserController.class);
	@Autowired
	private ParkUserService parkUserService;
	@Autowired
	private ParkOrderInfoService parkOrderInfoService;
	@Autowired
	private ParkingDeviceService parkingDeviceService;

	@RequestMapping(value = "/parkUser.do", params = "parkUser")
	public ModelAndView skipParkUser() {
		return new ModelAndView("parking/parkUser/parkUser_ftl");
	}

	@RequestMapping(value = "/parkUser.do", params = "loadList")
	@ResponseBody
	public Map<String, Object> loadList(ParkUserItem item, Pagination pg) {
		Map<String, Object> results = parkUserService.loadPageDataByConditions(
				pg, item, "findParkUserByCondition");
		return results;
	}

	@RequestMapping(value = "/parkUser.do", params = "editParkUser")
	@SystemControllerLog(description = "编辑")
	public ModelAndView editParkUser(HttpServletRequest request, Long parkUserId) {
		if (parkUserId != null) {
			request.setAttribute("parkUserItem",
					parkUserService.loadParkUserItem(parkUserId));
		}
		return new ModelAndView("parking/parkUser/editParkUser_ftl");
	}

	@RequestMapping(value = "/parkUser.do", params = "saveParkUser")
	@ResponseBody
	@SystemControllerLog(description = "保存")
	public ResultMessage saveParkUser(ParkUserItem item) {
		ResultMessage r = new ResultMessage();
		if (parkUserService.saveOrUpdateParkUser(item)) {
			r.setSuccess(true);
		} else {
			r.setSuccess(false);
		}
		return r;
	}

	@RequestMapping(value = "/parkUser.do", params = "deleteParkUserItems")
	@ResponseBody
	@SystemControllerLog(description = "删除")
	public ResultMessage deleteParkUserItems(String ids) {
		ResultMessage r = new ResultMessage();
		if (StringUtils.isNotEmpty(ids)) {
			String[] tempIds = ids.split(",");
			List<Long> parkUserIds = new ArrayList<Long>();
			for (String id : tempIds) {
				parkUserIds.add(Long.valueOf(id));
			}
			parkUserService.deleteParkUserInfo(parkUserIds);
			r.setSuccess(true);
		} else {
			r.setSuccess(false);
		}
		return r;
	}

	
	
	/******************* 以下是手机app接口调用方法 *********************/
	//http://localhost:8090/jmax/parkUser.action?login
	@RequestMapping(value = "/parkUser.action", params = "login")
	public void appLogin(HttpServletRequest request,
			HttpServletResponse response, String telephone, String password) {
		ResultMessage r = new ResultMessage();
		ParkUserItem parkUserItem = parkUserService.loginCheck(telephone, password);
		if (parkUserItem != null) {
			r.setMsg("登录成功");
			r.setObj(parkUserItem);
			request.getSession().setAttribute("parkUser", parkUserItem);
		} else {
			r.setSuccess(false);
			r.setMsg("账号或密码有误");
		}
		AppReturnUtils.returnJsonpAsk(request, response, r);
	}
	//http://localhost:8090/jmax/parkUser.action?logout
	@RequestMapping(value = "/parkUser.action", params = "logout")
	public void appLogout(HttpServletRequest request,
			HttpServletResponse response) {
		request.getSession().removeAttribute("parkUser");
		AppReturnUtils.returnJsonpAsk(request, response, new ResultMessage(
				true, "退出成功"));
	}
	//http://localhost:8090/jmax/parkUser.action?register&telephone=15059156856&password=123456&regCode&callback=?
	@RequestMapping(value = "/parkUser.action", params = "register")
	public void appRegister(HttpServletRequest request,
			HttpServletResponse response, String telephone, String password,String type,String regCode) {
		String sysRegCode = (String) request.getSession().getAttribute("regcode_"+telephone);
		ResultMessage rm = null;
		if ((sysRegCode+"").equals(regCode)) {
			rm = checkIsExist(telephone,password, request);
			if (rm.isSuccess()) {
				rm = join(telephone, password,type,request);
			}
		}else {
			rm = new ResultMessage();
			rm.setSuccess(false);
			rm.setMsg("验证码有误.");
		}
		
		AppReturnUtils.returnJsonpAsk(request, response, rm);
	}

	@RequestMapping(value = "/parkUser.action", params = "join")
	@ResponseBody
	public ResultMessage join(String telephone, String password,String type,HttpServletRequest request) {
		ResultMessage r = new ResultMessage();
//		if (StringUtils.isEmpty(nickName)) {
//			nickName = "Member";
//		}
		ParkUserItem parkUserItem = parkUserService.register(telephone,password,type);
		if (parkUserItem != null) {
			r.setMsg("注册成功");
			r.setObj(parkUserItem);
			request.getSession().setAttribute("parkUser", parkUserItem);
		} else {
			r.setMsg("注册失败");
			r.setSuccess(false);
		}
		return r;
	}
	
	@RequestMapping(value = "/parkUser.action", params = "getRegCode")
	public void appRegister(HttpServletRequest request,HttpServletResponse response, String telephone) {
		ResultMessage rm =new ResultMessage();
		//生成注册码
		String regCode = RandomStringUtils.random(6, "0123456789012345678901234567890123456789012345678901234567890123456789");
		rm.setObj(regCode);
		request.getSession().setAttribute("regcode_"+telephone, regCode);
		AppReturnUtils.returnJsonpAsk(request, response, rm);
	}

	@RequestMapping(value = "/parkUser.action", params = "checkIsExist")
	@ResponseBody
	public ResultMessage checkIsExist(String telephone, String password,
			HttpServletRequest request) {
		ResultMessage r = new ResultMessage();
		boolean isExist = parkUserService.checkTelephone(telephone);
		if (isExist) {
			r.setSuccess(false);
			r.setMsg("电话已存在,请直接登录.");
		} else {
			r.setSuccess(true);
		}
		return r;
	}


	@RequestMapping(value = "/parkUser.action", params = "updateUser")
	public void updateUser(ParkUserItem item,HttpServletRequest request,
			HttpServletResponse response) {
		ResultMessage r = new ResultMessage();
//		item.setPassword(DESCoder.encrypt(item.getPassword()));
		Object object = request.getSession().getAttribute("parkUser");
		if (object==null) {
			r.setSuccess(false);
			r.setMsg("用户未登录");
		}else {
			if (parkUserService.saveOrUpdateUser(item)) {
				request.getSession().setAttribute("parkUser", item);
				r.setSuccess(true);
				r.setMsg("更新完成");
			} else {
				r.setSuccess(false);
				r.setMsg("更新失败");
			}
		}
		
		AppReturnUtils.returnJsonpAsk(request, response, r);
	}
	
	@RequestMapping(value = "/parkUser.action", params = "updatePwd")
	public void updateUser(String telephone,String oldPwd,String newPwd,HttpServletRequest request,
			HttpServletResponse response) {
		ResultMessage r = new ResultMessage();
		Object object = request.getSession().getAttribute("parkUser");
		if (object==null) {
			r.setSuccess(false);
			r.setMsg("用户未登录");
		}else {
			String rs = parkUserService.updatePwd(telephone,oldPwd,newPwd);
			if (StringUtils.isBlank(rs)) {
				r.setSuccess(true);
			}else {
				r.setSuccess(false);
				r.setMsg(rs);
			}
		}
		
		AppReturnUtils.returnJsonpAsk(request, response, r);
	}
	
	/**
	 * 加载泊车编码信息
	 * 
	 * @author max.zheng
	 * @create 2015-6-27下午10:32:50
	 * @modified by
	 * @param parkNo
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/parkUser.action", params = "loadBillDetail")
	public void loadBillDetail(String aid,String parkNo,HttpServletRequest request,
			HttpServletResponse response) {
		ResultMessage r = new ResultMessage();
		Object object = request.getSession().getAttribute("parkUser");
		if (object==null) {
			r.setSuccess(false);
			r.setMsg("用户未登录");
		}else {
			BillDetail billDetail = parkUserService.getBillDetail(aid,parkNo);
			r.setObj(billDetail);
		}
		AppReturnUtils.returnJsonpAsk(request, response, r);
	}
	
	/**
	 * 提交生成预订单
	 * 
	 * @author max.zheng
	 * @create 2015-6-27下午11:32:34
	 * @modified by
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/parkUser.action", params = "createPreOrder")
	public void createPreOrder(String telephone,String totalFee,String parkNo,String aid,HttpServletRequest request,
			HttpServletResponse response) {
		ResultMessage r = new ResultMessage();
		Object object = request.getSession().getAttribute("parkUser");
		if (object==null) {
			r.setSuccess(false);
			r.setMsg("用户未登录");
		}else {
			String sysOrderNo = "p"+DateUtil.getDate(new Date(), DateStyle.YYYYMMDDHHMMSSSSS);
			int total = (int) (Double.valueOf(totalFee)*100);
			//prepay_id    sign
			Map<String, String> prepayMap = WeiXinPayUtil.createWeiXinPreOrder(total+"",sysOrderNo);
			log.info(prepayMap);
//			{result_code=SUCCESS, sign=F7FE9595030906447E731A03C8750B6B, mch_id=1250725301, prepay_id=wx201507012144239e72c8411d0797573609, return_msg=OK, appid=wx4461e99ba5b808ab, nonce_str=UtVtvf7Xhp2yuu24, return_code=SUCCESS, trade_type=APP}
			if ("SUCCESS".equals(prepayMap.get("result_code"))) {
				ParkUserItem parkUserItem = (ParkUserItem) object;
				BillDetail billDetail = new BillDetail(sysOrderNo,parkNo,totalFee,prepayMap.get("prepay_id"),prepayMap.get("sign"));
				billDetail.setAid(aid);
				parkOrderInfoService.savePreOrderInfo(billDetail,parkUserItem.getTelephone());
				//跳用微信预支付接口 
				r.getAttributes().put("prePayId", prepayMap.get("prepay_id"));
				r.getAttributes().put("sign", WeiXinPayUtil.genPaySign(prepayMap));
				r.getAttributes().put("sysOrderNo", sysOrderNo);
				r.getAttributes().put("parkNo", parkNo);
			}else {
				r.setSuccess(false);
				r.setMsg("生成预订单错误");
			}
			
		}
		AppReturnUtils.returnJsonpAsk(request, response, r);
	}
	
	@RequestMapping(value = "/parkUser.action", params = "paySuccessReturn")
	public void paySuccessReturn(String telephone,String sysOrderNo,String payPreId,HttpServletRequest request,
			HttpServletResponse response) {
		ResultMessage r = new ResultMessage();
		Object object = request.getSession().getAttribute("parkUser");
		if (object==null) {
			r.setSuccess(false);
			r.setMsg("用户未登录");
		}else {
			
			//prepay_id    sign
			//跳用微信预支付接口 
//			r.getAttributes().put("prepay_id", "wx201411101639507cbf6ffd8b0779950874");
//			r.getAttributes().put("sign", "7921E432F65EB8ED0CE9755F0E86D72F");
//			r.getAttributes().put("sysOrderNo", "p"+DateUtil.getDate(new Date(), DateStyle.YYYYMMDDHHMMSSSSS));
//			https://api.mch.weixin.qq.com/pay/orderquery
			ParkUserItem parkUserItem = (ParkUserItem) object;
			parkOrderInfoService.update(payPreId,parkUserItem.getTelephone());
		}
		AppReturnUtils.returnJsonpAsk(request, response, r);
	}
	
	@RequestMapping(value = "/parkUser.action", params = "vipOperation")
	public void vipOperation(String aid,String parkNo,String operationType,HttpServletRequest request,
			HttpServletResponse response) {
		ResultMessage r = new ResultMessage();
		Object object = request.getSession().getAttribute("parkUser");
		if (object==null) {
			r.setSuccess(false);
			r.setMsg("用户未登录");
		}else {
			ParkUserItem parkUserItem = (ParkUserItem) object;
//			parkOrderInfoService.update(payPreId,parkUserItem.getTelephone());
			r.setSuccess(parkingDeviceService.operation(aid, parkNo, operationType));
		}
		AppReturnUtils.returnJsonpAsk(request, response, r);
	}

}
